/*
 * This file is part of algowala.
 *
 * algowala is copyright (c) 2012 Jagannathan Sampath <algowala@jagernot.com>
 *
 * algowala is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * algowala is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with algowala.  If not, see <http://www.gnu.org/licenses/>.
 *
*/

#include "tcp_server.h"
#include "ansi_color_codes.h"
#include <string.h>
#include <iostream>
#include <string>
#include <stdio.h>
#include <fcntl.h>
using namespace std;

extern std::string APP_NAME;

tcp_server::tcp_server (int _port) {
  
  port = _port; // server listens at this port
  
  // server boilerplate
  sockaddr_in server;
  server.sin_family = AF_INET;
  server.sin_port = htons (port);
  server.sin_addr.s_addr = INADDR_ANY;
  bzero(&(server.sin_zero), 8);
  
  sock = socket (AF_INET, SOCK_STREAM, 0); // create socket
  
  if (sock == -1) {
    cout << FAIL << "!!! couldnt open TCP socket !!!" << ENDL;
  } else {
    int _true = 1;
    if ( setsockopt (sock, SOL_SOCKET, SO_REUSEADDR, &_true, sizeof(int)) == -1) {
      perror("setsockopt");
      cout << FAIL << "!!! couldnt set socket options !!!" << ENDL;
    }
    fcntl (sock, F_SETFL, O_NONBLOCK); // make socket non-blocking
  }
  
  // bind socket to port
  if (bind (sock, (sockaddr *) &server, sizeof (sockaddr)) == -1) {
    perror ("bind");
    cout << FAIL << "couldnt setup TCP server to listen at port " << port << endl;
    sock = -1;
  } else {
    cout << PASS << APP_NAME << " TCP server waiting for commands at port " << port << std::endl;
  }
  
  // get ready to listen
  const int backlog = 5;
  if (listen (sock, backlog) == -1) {
    perror("listen");
    sock = -1;
  }
  
  thrd = 0; // listen for connections in separate thread (see run (..))

}

void tcp_server::start () { // start the server
  if ((sock != -1) && (thrd == 0)) {
    quit_thread = 0;
    pthread_create (&thrd, 0, tcp_server::run, this);
  }
}

void tcp_server::stop () { // stop the server
  if (sock != -1) {
    tcp_server::quit_thread = 1;
    pthread_join (thrd, 0);
    cout << PASS << APP_NAME << " TCP server is now closed" << endl;
  }
}

void* tcp_server::run (void* arg) {
  
  // for recieving data
  static const int recv_buf_size = 1024;
  char recv_buf [recv_buf_size];
  int bytes_read = 0;

  tcp_server* srv = static_cast<tcp_server*> (arg);
  
  sockaddr_in client;
  socklen_t sin_size = sizeof(sockaddr_in);
  int connected = -1;
  
  while (quit_thread == 0) {
    
    connected = accept (srv->sock, (sockaddr *) &client, &sin_size); // accept incoming connection
    
    if (connected > 0) {
      srv->connections.push_back (connected); // add connection to array of active connections
      fcntl (connected, F_SETFL, O_NONBLOCK); // make connection non-blocking
    }
    
    for (int i = 0, j = srv->connections.size (); i < j; ++i) { // read waiting data on the active connections
      
      string cmd;
      
      while ((bytes_read = recv (srv->connections[i], recv_buf, recv_buf_size, 0)) > 0) {
        recv_buf [bytes_read] = '\0';
        cmd += recv_buf;
      }
      
      if (cmd != "") srv->push (srv->connections[i], cmd);
    
    }
    
    usleep (1);

  }
  
  for (int i = 0, j = srv->connections.size (); i < j; ++i) close (srv->connections[i]);
  close (srv->sock);
  
  return 0;
  
}


